import telnetlib, logging, time  # noqa: E401
from bk_check_conf import server_list

import requests  # type: ignore
from datetime import datetime  # type: ignore


# 定义一个类用来执行巡检
class InspectServer:
    def __init__(self):
        # 巡检日志文件
        self.log_file = "log.txt"

    # 定义Telnet命令函数
    def telnet_command(
        self,
        tn,
        command,
        wait_time,
    ):
        tn.write(command + b"\n")
        time.sleep(wait_time)
        output = tn.read_very_eager().decode("utf-8")
        return output

    def inspect_server_login(
        self,
        server,
    ):
        # 连接服务器
        try:
            tn = telnetlib.Telnet(server["address"], server["port"], timeout=5)
        except Exception:
            self.log_ins_file("error", "{}: {}连接失败, 可能没开机...".format(server["name"], server["address"]))
            return None
        else:
            self.log_ins_file("info", "{}: {}连接成功, 登录中...".format(server["name"], server["address"]))

        # 登录
        tn.read_until(b"login:")
        tn.write(server["login_user"].encode("ascii") + b"\n")
        tn.read_until(b"Password:")
        tn.write(server["login_password"].encode("ascii") + b"\n")

        # 判断服务器是否登录成功
        result = tn.read_until(b"Welcome to HiLinux.")
        if b"Welcome to HiLinux." not in result:
            # 如果服务器没有开机，写入错误日志文件
            self.log_ins_file("error", "{}: {}服务器登录失败".format(server["name"], server["address"]))
            return None
        else:
            self.log_ins_file("info", "{}: {}服务器登录成功".format(server["name"], server["address"]))
            return tn

    # 写入日志函数
    def log_ins_file(self, log_type, log_txt):
        # 设置log日志文件位置、格式
        logging.basicConfig(
            filename=self.log_file,
            format="%(asctime)s %(levelname)s :%(message)s",
            level=logging.INFO,
            encoding="utf-8",
        )
        print(log_txt)
        if log_type == "info":
            logging.info(log_txt)
        elif log_type == "error":
            logging.error(log_txt)
        logging.shutdown()


# 实例化
inspect = InspectServer()


def main():
    inspect_server_login = inspect.inspect_server_login

    # 本次巡检列表
    inspect.log_ins_file("info", "本次巡检列表共{}个".format(len(server_list)))
    print(
        """
    1、巡检硬盘挂载情况(只列出硬盘容量)
    2、巡检硬盘使用情况(只列出已经使用容量)
    3、巡检时间(只查看)
    4、巡检时间(进行校时: 以本机时间进行校对)
    5、测试读写速度(生成一个512Mb的文件)
    6、查看硬盘型号
    7、删除所有硬盘空间
    8、重启
    9、自定义命令
    """
    )
    ins_menu_input = input("请问要做什么: ")
    # 根据输入选项, 放在循环内是因为部分值是动态的
    if ins_menu_input == "1":
        command = "echo $(df -h | awk 'NR=-1{print $2}')"
        # command = b"echo $(df -h)"
        wait_time = 3
    elif ins_menu_input == "2":
        # command = b"echo $(df -h | awk 'NR=-1{print $3}')"
        command = "df -h|grep /srv"
        wait_time = 2
    elif ins_menu_input == "3":
        command = 'date "+%Y-%m-%d %H:%M:%s"'
        wait_time = 2
    elif ins_menu_input == "4":
        local_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))
        print(local_time)
        command = 'date -s "{}"'.format(local_time)
        wait_time = 2
    elif ins_menu_input == "5":
        # 生成一个512Mb的文件
        command = "dd if=/dev/zero bs=1024 count=512000 of=/srv/512Mb.file && dd if=/srv/512Mb.file bs=64k of=/dev/null && rm -f /srv/512Mb.file"
        # dd if=/srv/256Mb.file bs=64k | dd of=/dev/null
        wait_time = 35
    elif ins_menu_input == "6":
        command = 'hdparm -I /dev/sda | grep "Model Number"'
        wait_time = 3
    elif ins_menu_input == "7":
        command = "rm -rf /srv/bwrecord/lessonrecord/*"
        wait_time = 90
    elif ins_menu_input == "8":
        command = "reboot"
        wait_time = 2
    elif ins_menu_input == "9":
        command = input("请输入需要执行的命令(自定义): ")
        wait_time = int(input("请输入命令执行大致等待时间(如阻塞类命令值可以输入大一些): "))
    else:
        print("输入错误, 程序终止")
        exit()

    for server in server_list:
        # local_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))
        # print(local_time)
        # command = 'date -s "{}"'.format(local_time)
        # wait_time = 2
        tn = inspect_server_login(server)
        if tn is None:
            continue
        result = inspect.telnet_command(tn, command=command.encode("utf-8"), wait_time=wait_time)
        inspect.log_ins_file("info", result)

        tn.close()
        # rm -rf /srv/bwrecord/lessonrecord/*


if __name__ == "__main__":
    main()
